package com.ycy.lucene.plugin;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.spell.PlainTextDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;

import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;

/**
 * lucene 提供的 纠错功能
 */
public class SpellCheckTest {


  private static String dicpath = "D:\\Users\\yincy\\Desktop\\spellcheck.dic";
  private Document document;
  private Directory directory = new RAMDirectory();


  private IndexWriter indexWriter;
  /**
   * 拼写检查器
   */
  private SpellChecker spellchecker;
  private IndexReader indexReader;
  private IndexSearcher indexSearcher;

  public SpellCheckTest() {
    try {
//      directory = FSDirectory.open(Paths.get("/Users/ycy/Desktop/yin/lucene_index"));
      this.spellchecker = new SpellChecker(directory);
      this.spellchecker.setAccuracy(0.8f);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 创建测试索引
   *
   * @param content
   * @throws IOException
   */
  public void writeIndex(String content) throws IOException {
    IndexWriterConfig config = new IndexWriterConfig();
//    indexWriter = new IndexWriter(directory, config);
//    document = new Document();
//    document.add(new TextField("content", content, Store.YES));
//    try {
//      indexWriter.addDocument(document);
//      indexWriter.commit();
//      indexWriter.close();
//    } catch (IOException e) {
//      e.printStackTrace();
//    }

    spellchecker.indexDictionary(new PlainTextDictionary(new StringReader(content)), config, true);

  }

  public void search(String word, int numSug) {
//    directory = new RAMDirectory();
    try {
//      IndexWriterConfig config = new IndexWriterConfig(new StandardAnalyzer());
//      spellchecker = new SpellChecker(directory);
//      spellchecker.setAccuracy(0.8f);
      //初始化字典目录
      //最后一个fullMerge参数表示拼写检查索引是否需要全部合并
//      spellchecker.indexDictionary(new PlainTextDictionary(Paths.get(dicpath)), config, true);

      //这里的参数numSug表示返回的建议个数
      String[] suggests = spellchecker.suggestSimilar(word, numSug);
      if (suggests != null && suggests.length > 0) {
        for (String suggest : suggests) {
          System.out.println("您是不是想要找：" + suggest);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

//  public void createSpellIndex(String oriIndexPath, String fieldName,
//                               String spellIndexPath) throws IOException {
//    IndexReader oriIndex = IndexReader.open(FSDirectory.open(new File(oriIndexPath)));
//    LuceneDictionary dict = new LuceneDictionary(oriIndex, fieldName);
//    Directory spellIndexDir = FSDirectory.open(new File(spellIndexPath));
//    SpellChecker spellChecker = new SpellChecker(spellIndexDir);
//    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, null);
//    spellChecker.indexDictionary(dict, config, true);
//  }

  public static void main(String[] args) throws IOException {
    SpellCheckTest spellCheckTest = new SpellCheckTest();
    spellCheckTest.writeIndex("《屌丝男士》不是传统意义上的情景喜剧，有固定时长和单一场景，以及简单的生活细节。而是一部具有鲜明网络特点，舞台感十足，整体没有剧情衔接，固定的演员演绎着并不固定角色的笑话集。");
    spellCheckTest.writeIndex("屌丝男士的拍摄构想，首先源于“屌丝文化”在中国的刮起的现象级春风，红透了整片天空，全中国上下可谓无人不屌丝，无人不爱屌丝。");
    spellCheckTest.writeIndex("德国的一部由女演员玛蒂娜-希尔主演的系列短剧，凭借其疯癫荒诞、自high耍贱、三俗无下限的表演风格，在中国取得了巨大成功，红火程度远远超过了德国。");

    String word = "吊丝男士屌丝男士";
    spellCheckTest.search(word, 5);

    Directory directory = spellCheckTest.directory;
    DirectoryReader open = DirectoryReader.open(directory);
//    IndexSearcher indexSearcher = new IndexSearcher(open);

    //遍历所有 term
    int i = open.maxDoc();
    for (int j = 0; j < i; j++) {
      Document document = open.document(j);
      System.out.println(document);
      //这个不知道干嘛的？
      Fields termVectors = open.getTermVectors(j);
      if (termVectors != null) {
        Iterator<String> iterator = termVectors.iterator();
        while (iterator.hasNext()) {
          System.out.println(iterator.next());
        }
        System.out.println(termVectors);

      }
    }

    List<LeafReaderContext> leaves = open.leaves();
    for (LeafReaderContext leaf : leaves) {
      LeafReader reader = leaf.reader();
      //获取文档中使用的字段
      FieldInfos fieldInfos = reader.getFieldInfos();
      for (FieldInfo fieldInfo : fieldInfos) {
        System.out.println("fileName：" + fieldInfo.name);
        //通过字段获取索引中的term
        Terms terms = reader.terms(fieldInfo.name);
        TermsEnum iterator = terms.iterator();
        while (true) {
          BytesRef byteRef = iterator.next();
          if (byteRef == null) break;

          String term = new String(byteRef.bytes, byteRef.offset, byteRef.length);
          System.out.println(term);
        }
      }
    }


  }

}
